package com.ib.review.repository.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.ib.review.mapper.KnowledgeBaseMapper;
import com.ib.review.pojo.dto.KnowledgeParam;
import com.ib.review.pojo.dto.KnowledgeQuery;
import com.ib.review.pojo.po.KnowledgeBasePO;
import com.ib.review.repository.KnowledgeRepository;
import jakarta.annotation.Resource;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.stereotype.Repository;

import java.util.List;

@Repository
public class KnowledgeRepositoryImpl implements KnowledgeRepository {
    @Resource
    private KnowledgeBaseMapper knowledgeBaseMapper;

    public Page<KnowledgeBasePO> query(KnowledgeQuery knowledgeQuery) {
        Page<KnowledgeBasePO> page = new Page<>(knowledgeQuery.getPageNo(), knowledgeQuery.getPageSize());
        LambdaQueryWrapper<KnowledgeBasePO> queryWrapper = new LambdaQueryWrapper<>();
        String condition = knowledgeQuery.getKnowledgeName();
        queryWrapper.eq(KnowledgeBasePO::getDelFlag,0);
        queryWrapper.eq(KnowledgeBasePO::getType,1);
        queryWrapper.like(condition!=null && !condition.isEmpty(),KnowledgeBasePO::getKnowledgeName,
                knowledgeQuery.getKnowledgeName());
        queryWrapper.orderByDesc(KnowledgeBasePO::getCreateTime);
        return knowledgeBaseMapper.selectPage(page, queryWrapper);
    }

    public void add(KnowledgeBasePO po) {
        knowledgeBaseMapper.insert(po);
    }

    public void delete(String knowledgeId) {
        knowledgeBaseMapper.updateDelFlag(knowledgeId);
    }

    public void edit(KnowledgeBasePO knowledgeParam) {
        knowledgeBaseMapper.edit(knowledgeParam);
    }

    public void batchDelete(List<String> ids) {
        LambdaUpdateWrapper<KnowledgeBasePO> updateWrapper = new LambdaUpdateWrapper<>();
        updateWrapper.set(KnowledgeBasePO::getDelFlag, 1);
        updateWrapper.in(KnowledgeBasePO::getKnowledgeId, ids);
        knowledgeBaseMapper.update(updateWrapper);
    }

    public void batchInsert(List<KnowledgeBasePO> list) {
        if (CollectionUtils.isNotEmpty(list)) {
            knowledgeBaseMapper.insertBatch(list);
        }
    }

    public Integer selectCountByName(KnowledgeParam knowledgeParam) {
        return knowledgeBaseMapper.queryCount(knowledgeParam);
    }

    public KnowledgeBasePO queryByName(KnowledgeParam knowledgeParam) {
        return knowledgeBaseMapper.queryByName(knowledgeParam);
    }
}
